package zdream.control.foe.mm2pipi;

import zdream.control.world.buff.HealthModule;
import zdream.control.world.LevelWorld;
import zdream.control.world.MFoe;
import zdream.control.world.buff.StageModule;
import zdream.control.world.TerrainHandler;
import zdream.control.world.Ticker;

/**
 * <p>2 代带着蛋飞的鸟.
 * <p>
 * <li>飞行速度: 水平方向 8 p/s
 * <li>携带一只蛋
 * <li>HP:1, 碰撞伤害:无
 * <li>侦测: 敌人到达横纵坐标差为 10 块时把蛋放下, 仅触发一次
 * </li></p>
 * 
 * @author Zdream
 * @since 0.0.1
 * @date 2020-06-11 (created)
 * @date 2022-06-11 (last modified)
 */
public class MM2Pipi extends MFoe {
	public static final String NAME = "MM2Pipi";

	public MM2Pipi(LevelWorld world) {
		super(world);
		this.type = TYPE_FOE;
		this.side = SIDE_ENEMY;
	}

	@Override
	public String foeName() {
		return NAME;
	}

	@Override
	public void init() {
		createNormalPattern()
				// 锚点在下底的中点偏左
				.withRectangle(-0.4583f, 0, 0.9583f, 0.8f)
				.apply();
		healthModule = buildHealthModule()
				.outsideDestroyThreshold(1000)
				.hpMax(1)
				.create();
		stageModule = buildStageModule()
				.defineInitStage(STAGE_BEGIN, this::handleBeginStage)
				.defineStage(STAGE_END, this::handleEndStage)
				.create();

		terrainHandler = new TerrainHandler(world);
		terrainHandler.floating = true;

		// 它携带一只蛋
		egg = new MM2PipiEgg(this);
		world.createFoe(egg, anchorX, anchorY, orientation);
		onClean(this::beforeDestroy);
	}

	public HealthModule healthModule;
	public StageModule stageModule;

	/* **********
	 *   阶段   *
	 ********** */
	public static final String STAGE_BEGIN = "begin";
	public static final String STAGE_END = "end";

	private void handleBeginStage(StageModule s, Ticker ticker) {
		moveSelf(ticker);

		if (egg == null) {
			s.changeStageTo(STAGE_END);
			return;
		}

		float px = orientation ? anchorX : anchorX - 10;
		MFoe enemy = s.findNearestEnemy(px, anchorY - 10, 10, 10);
		if (enemy == null) {
			return;
		}
		float distanceX = Math.abs(anchorX - enemy.getCenterX());
		if (distanceX < 4) {
			throwEgg();
			s.changeStageTo(STAGE_END);
		}
	}

	private void handleEndStage(StageModule s, Ticker ticker) {
		moveSelf(ticker);
	}

	private void moveSelf(Ticker ticker) {
		velocityX = vx * ticker.duration;
		velocityY = 0;
		terrainHandler.submitFloatBoxMotion(this);

		// 接下来是蛋的
		if (egg != null) {
			if (egg.isDestroyed()) {
				egg = null;
			} else {
				egg.setPosition(anchorX, anchorY);
			}
		}
	}

	/* **********
	 *   盒子   *
	 ********** */
	private float vx;

	/**
	 * 生怪场调用的
	 */
	public void setVX(float vx) {
		this.vx = vx;
		flush();
	}

	/* **********
	 *   携带   *
	 ********** */

	MM2PipiEgg egg;

	protected void beforeDestroy(MFoe self) {
		if (egg != null) {
			egg.destroy();
		}
	}

	private void throwEgg() {
		egg.thrown();
		egg = null;
	}
}
